# coding:utf8

from appserver import db_store
from sqlalchemy.orm import relationship, backref
from sqlalchemy import or_
from models.entity.model_base import ModelBase

"""
模块数据模型
"""


class Dict(ModelBase):
    __tablename__ = "dcits"
    __bind_key__ = "main"

    # autoincrement=True,
    id = db_store.Column(db_store.Integer, primary_key=True, comment=u'字典项ID')
    name = db_store.Column(db_store.String(64), nullable=False, unique=True, comment=u'字典项名称')
    code = db_store.Column(db_store.String(32), nullable=False, unique=True, comment=u"字典项编码")
    cate_id = db_store.Column(db_store.Integer, db_store.ForeignKey('dcit_categorys.id'), nullable=False, comment=u"字典分类ID")
    dict_value = db_store.Column(db_store.String(255), comment=u"字典项值")
    pinyin = db_store.Column(db_store.String(100), comment=u"字典项拼音")
    description = db_store.Column(db_store.String(255), comment=u"描述")
    dis_order = db_store.Column(db_store.Integer, comment=u"排序")
    status = db_store.Column(db_store.Integer, comment=u"状态")  # 0-正常 1-禁用
    DictCategory = relationship("DictCategory", backref=backref('dcit_categorys', order_by=id))

    def __repr__(self):
        return "<Dict %s>" % self.name

    @staticmethod
    def get_dict_by_id(id_num):
        return Dict.query.filter_by(id=id_num).first()

    @staticmethod
    def get_dict_by_name(name):
        return Dict.query.filter_by(name=name).first()

    @staticmethod
    def get_dict_by_code(code):
        return Dict.query.filter_by(code=code).first()

    @staticmethod
    def get_dicts_by_cate_id(cate_id):
        return Dict.query.filter_by(cate_id=cate_id).all()

    @staticmethod
    def get_dict_all():
        return Dict.query.all()

    @staticmethod
    def search(query_word):
        data = []
        buttons = Dict.query.filter(
            or_(Dict.code.like('%' + query_word + '%'), Dict.name.like('%' + query_word + '%'),
                Dict.description.like('%' + query_word + '%'),Dict.pinyin.like('%' + query_word + '%'),
                Dict.dict_value.like('%' + query_word + '%'))).all()
        for obj in buttons:
            data.append({"id": obj.id, "name": obj.name, "code": obj.code, "description": obj.description,
                       "pinyin": obj.pinyin, "status": obj.status, "dict_value": obj.dict_value})
        return data